package com.aigou.compont;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.aigou.pojo.Goods;
import com.aigou.pojo.Result;
import com.aigou.pojo.SkillGoods;
import com.aigou.service.ISkillGoodsService;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Component
public class SkillGoodsCompoent {

	@Autowired
	StringRedisTemplate redisTemplate;
	@Autowired
	ISkillGoodsService skillGoodsService;
	
	static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
	
	public static void main(String[] args) {
		System.out.println(sdf.format(new Date()));
	}
	
	 @Scheduled(cron = "0 20 14,16,18 * * ?")
	public void initGoodsToRedis() {
		 
		Date date = new Date();
		String time = sdf.format(date);
		
		QueryWrapper<SkillGoods> query = new QueryWrapper<>();
		query.eq("skill_time", time);
		List<SkillGoods> dbGoodslist = skillGoodsService.list(query);
		
		dbGoodslist.forEach((g) -> {
			redisTemplate.opsForHash().put("skill:goods:list", g.getId() + "", JSON.toJSONString(g));
			Integer num = g.getSkillNum();
			for (int i = 0; i < num; i++) {
				// 防止超卖
				redisTemplate.opsForList().leftPush("skill:goods:" + g.getId(), g.getId() + "");
			}
			// 库存扣减原子性
			redisTemplate.opsForValue().set("skill:goods:num:" + g.getId(), num + "");
		});
	}
	
}
